import { ERROR_MESSAGE, EVENT_KEYS } from "@/common/constants";
import { showMessage } from "@/common/utils";
import { router } from "@/router";
import EventBus from "./eventBus";
import { getRedirectPath } from "@/router/permission";

/**
 * 初始化全局事件监听
 */
export const initGlobalEventListeners = () => {
	// 未授权事件监听
	EventBus.$on(EVENT_KEYS.UNAUTHORIZED, () => {
		const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const currentPath = currentPage ? currentPage.route : '';
		const currentFullPath = currentPage ? currentPage.__page__.fullPath : '';
		showMessage(ERROR_MESSAGE.UNAUTHORIZED + ", 1秒后将跳转至登录页", false);
		const redirect = getRedirectPath('/' + currentPath);
		setTimeout(() => {
			router.push({
				path: redirect,
				query: {
					redirect: currentFullPath
				}
			});
		}, 1000);
	});

	// 网络错误事件监听
	EventBus.$on(EVENT_KEYS.NETWORK_ERROR, () => {
		showMessage(ERROR_MESSAGE.NETWORK_ERROR, false);
	});
};

/**
 * 清理全局事件监听
 */
export const clearGlobalEventListeners = () => {
	EventBus.$off(EVENT_KEYS.UNAUTHORIZED);
	EventBus.$off(EVENT_KEYS.NETWORK_ERROR);
};
